/*
 * Copyright (c) 2023 - present Dromara, All rights reserved.
 *
 *   https://visor.dromara.org
 *   https://visor.dromara.org.cn
 *   https://visor.orionsec.cn
 *
 * Members:
 *   Jiahang Li - ljh1553488six@139.com - author
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ruoyi.visor.module.terminal.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.visor.common.constant.Const;
import com.ruoyi.visor.module.infra.entity.dto.data.DataGroupCreateDTO;
import com.ruoyi.visor.module.infra.entity.dto.data.DataGroupDTO;
import com.ruoyi.visor.module.terminal.entity.request.snippet.CommandSnippetGroupCreateRequest;
import com.ruoyi.visor.module.terminal.entity.vo.CommandSnippetGroupVO;
import lombok.extern.slf4j.Slf4j;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.visor.module.infra.api.DataGroupUserApi;
import com.ruoyi.visor.module.infra.enums.DataGroupTypeEnum;
import com.ruoyi.visor.module.terminal.convert.CommandSnippetGroupConvert;
import com.ruoyi.visor.module.terminal.service.CommandSnippetGroupService;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 命令片段分组 服务实现类
 *
 * @author Jiahang Li
 * @version 1.0.0
 * @since 2024-1-24 12:28
 */
@Slf4j
@Service
public class CommandSnippetGroupServiceImpl implements CommandSnippetGroupService {


    @Resource
    private DataGroupUserApi dataGroupUserApi;


    @Override
    public Long createCommandSnippetGroup(CommandSnippetGroupCreateRequest request) {
        Long userId = SecurityUtils.getUserId();
        log.info("CommandSnippetGroupService-createCommandSnippetGroup request: {}", JSON.toJSONString(request));
        // 创建
        DataGroupCreateDTO create = CommandSnippetGroupConvert.MAPPER.to(request);
        create.setParentId(Const.ROOT_PARENT_ID);
        return dataGroupUserApi.createDataGroup(DataGroupTypeEnum.COMMAND_SNIPPET, userId, create);
    }


    @Override
    public List<CommandSnippetGroupVO> getCommandSnippetGroupList() {
        Long userId = SecurityUtils.getUserId();
        // 查询分组
        return dataGroupUserApi.getDataGroupList(DataGroupTypeEnum.COMMAND_SNIPPET, userId)
                .stream()
                .sorted(Comparator.comparing(DataGroupDTO::getSort))
                .map(CommandSnippetGroupConvert.MAPPER::to)
                .collect(Collectors.toList());
    }


}
